package com.fita.wechat.web.controller.authority;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import com.demo2do.core.utils.JsonUtils;
import com.demo2do.core.utils.StringUtils;
import com.demo2do.core.web.handler.CookieHandler;
import com.demo2do.core.wechat.entity.auth.WebAuthLogin;
import com.fita.wechat.Constant;
import com.fita.wechat.processor.WechatProcessor;

/**
 * 
 * @author mohanlan
 *
 */
@Controller()
@RequestMapping("/auto-login")
public class AutoLoginController {
    
    private static final Logger logger = LoggerFactory.getLogger(AutoLoginController.class);
    
    public static final String OPENID = Constant.OPENID_KEY;
    
    public static final String MOBILE = "mobile";
    
    public static final String UNIONID = Constant.UNIONID_KEY;
    
    public static final String USER_ACCOUNT = Constant.USER_ACCOUNT_KEY;
    
    public static final int EXPIRE_TIME = 1080 * 24 * 3600;
    
    @Autowired
    private WechatProcessor wechatProcessor;
    
    @Autowired
    private CookieHandler cookieHandler;
    
    /*
     * @Autowired private AgentService agentService;
     */
    
    /**
     * Auto login view
     * 
     * @param uuid
     * @param response
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String autoLogin(@RequestParam("uuid") String uuid, HttpServletResponse response) {
        
        logger.info("#autoLogin() get request param uuid [{}]", uuid);
        
        // 1. get remote web_auth 
        WebAuthLogin login = wechatProcessor.login(uuid);
        
        logger.info("#autoLogin() get login [{}]", JsonUtils.toJson(login));
        
        if(login.isValid()) {
            
            // 2. get openid and put into cookie
            String openid = login.getOpenid();
            logger.info("#autoLogin() get openid from login [{}]", openid);
            cookieHandler.addCookie(response, OPENID, openid, EXPIRE_TIME);
            
           // 3. redirect according to redirect_url
           logger.info("#autoLogin redirect to page [{}]", login.getRedirectUrl());
           return StringUtils.connect("redirect:", login.getRedirectUrl());
           
        }
        
        // redirect to internal error page
        logger.error("#autoLogin - An error occurs when doing remote login by uuid [{}]", uuid);
        
        return "redirect:/auto-login/error";
        
    }
    
    /**
     * @return
     */
    @RequestMapping(value = "/error", method = RequestMethod.GET)
    public String error() {
        return "auth/auth-error";
    }
}
